package com.ruoyi.framework.aspectj;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.DataSelfScope;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 数据过滤处理
 *
 * @author ruoyi
 */
@Aspect
@Component
@Slf4j
public class DataSelfScopeAspect {

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 数据范围过滤
     *
     * @param joinPoint  切点
     * @param user       用户
     * @param permission 权限字符
     */
    @SneakyThrows
    public void dataScopeFilter(
            JoinPoint joinPoint,
            SysUser user,
            String permission) {
        Object[] args = joinPoint.getArgs();
        String json = objectMapper.writeValueAsString(args);
        JSONArray jsonObject = JSONArray.parseArray(json);
        JSONObject jsonObject1 = (JSONObject) jsonObject.get(0);

        if (!Objects.equals(user.getUserName(), jsonObject1.get(permission))) {
            throw new ServiceException("当前用户无操作权限");
        }
    }

    @Before("@annotation(controllerDataScope)")
    public void doBefore(JoinPoint point, DataSelfScope controllerDataScope) throws Throwable {
        handleDataScope(point, controllerDataScope);
    }

    protected void handleDataScope(final JoinPoint joinPoint, DataSelfScope controllerDataScope) {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(loginUser)) {
            SysUser currentUser = loginUser.getUser();
            // 如果是超级管理员，则不过滤数据
            if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) {
                dataScopeFilter(
                        joinPoint,
                        currentUser,
                        controllerDataScope.permissionColumn());
            }
        }
    }

}
